package com.gxuwz.ssy.common;

import com.gxuwz.ssy.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;

import javax.servlet.http.HttpServletRequest;

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启方法级安全验证(通过注解在controller的方法)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private CustomUserDetailsService userDatailService;

    @Autowired
    private MyAuthenticationProvider myAuthenticationProvider;

    @Autowired
    private AuthenticationDetailsSource<HttpServletRequest, WebAuthenticationDetails> authenticationDetailsSource;



    /**
     * 指定加密方式
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        // 使用BCrypt加密密码
        return new BCryptPasswordEncoder();
    }

    /**
     * 用户认证
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 从数据库读取的用户进行身份认证
        auth.userDetailsService(userDatailService)
                .passwordEncoder(passwordEncoder());
        // 这里需要把我们自定义的核心验证方法装配进去使用
        auth.authenticationProvider(myAuthenticationProvider);



    }




    /**
     * 这里用来配置我们自定义的登录页面
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //super.configure(http);
        http.formLogin()
                .loginProcessingUrl("/api/check") // 登录访问路径
                .loginPage("/login.html")   //自定义登录页面
                .defaultSuccessUrl("/index")  // 登录成功后url
                .authenticationDetailsSource(authenticationDetailsSource)  //自定义的资源要配置进去
                .and()
                .authorizeRequests()
                .antMatchers("/login.html").permitAll() // 放行/login.html                .failureUrl("/login/error") // 处理异常的controller
                .and().csrf().disable();  //关闭csrf防护


        //启用注销功能，（需要提供一个action为/logout的form）并设置注销后访问的url，这里注销后跳转到登录页
        http.logout().logoutSuccessUrl("/login");


    }


}
